package cn.wp.common.core.id;

import cn.wp.common.core.exception.WpException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * ID 配置
 * Created by chenyb on 2019/09/24
 */
@Configuration
@Slf4j
public class IdConfiguration {

    @Autowired
    private IdProperties idProperties;

    private String logPrefix = "[wp.common.id]";

    @Bean
    public SnowflakeIdWorker snowflakeIdWorker(){
        int wordId = idProperties.getWordId();
        int dataCenterId = idProperties.getDataCenterId();
        if(wordId < 0 || wordId > 31){
            throw new WpException(logPrefix + " wordId value range 0-31");
        }

        if(dataCenterId < 0 || dataCenterId > 31){
            throw new WpException(logPrefix + " dataCenterId value range 0-31");
        }

        if(wordId == 0){
            log.warn("{} wordId may not be initialized , default value is 0 ",logPrefix);
        }else{
           log.info("{} wordId = {}",logPrefix,wordId);
        }

        if(dataCenterId == 0){
            log.warn("{} dataCenterId may not be initialized , default value is 0 ",logPrefix);
        }else{
            log.info("{} dataCenterId = {}",logPrefix,dataCenterId);
        }

        SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(wordId,dataCenterId);
        return snowflakeIdWorker;
    }

}
